#include "KeyboardHook.h"
#include "DataManager.h"

// Static member initialization
KeyboardHook* KeyboardHook::s_instance = nullptr;

KeyboardHook::KeyboardHook()
    : m_hhook(nullptr)
    , m_dataManager(nullptr)
    , m_clickCallback(nullptr)
{
    s_instance = this;
}

KeyboardHook::~KeyboardHook() {
    UninstallHook();
    s_instance = nullptr;
}

bool KeyboardHook::InstallHook() {
    if (m_hhook) {
        return true; // Already installed
    }
    
    m_hhook = SetWindowsHookEx(
        WH_KEYBOARD_LL,
        LowLevelKeyboardProc,
        GetModuleHandle(nullptr),
        0
    );
    
    if (!m_hhook) {
        DWORD error = GetLastError();
        // Note: We can't use std::cout here because this might be called before console is set up
        return false;
    }
    return true;
}

void KeyboardHook::UninstallHook() {
    if (m_hhook) {
        UnhookWindowsHookEx(m_hhook);
        m_hhook = nullptr;
    }
}

int KeyboardHook::GetClickCount() const {
    if (m_dataManager) {
        return m_dataManager->GetCurrentClickCount();
    }
    return 0;
}

void KeyboardHook::OnKeyPressed() {
    // Delegate to DataManager for counting and saving
    if (m_dataManager) {
        m_dataManager->OnKeyPressed();
        
        int newCount = m_dataManager->GetCurrentClickCount();
        
        // Notify callback with updated count
        if (m_clickCallback) {
            m_clickCallback(newCount);
        }
    }
}

LRESULT CALLBACK KeyboardHook::LowLevelKeyboardProc(int nCode, WPARAM wParam, LPARAM lParam) {
    if (nCode >= 0) {
        // Check if it's a key down event
        if (wParam == WM_KEYDOWN || wParam == WM_SYSKEYDOWN) {
            if (s_instance) {
                s_instance->OnKeyPressed();
            }
        }
    }
    
    // Call next hook
    return CallNextHookEx(nullptr, nCode, wParam, lParam);
}
